package com.grayscale.dashboard.service.impl;

import com.github.pagehelper.PageInfo;
import com.grayscale.core.enums.GrayScaleTypeEnum;
import com.grayscale.dashboard.service.RuleService;
import com.grayscale.dashboard.util.StringUtils;
import com.grayscale.dashboard.vo.RuleVo;
import com.grayscale.dashboard.web.base.BaseService;
import com.grayscale.dashboard.web.page.PageDomain;
import com.grayscale.dashboard.web.page.TableDataInfo;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author liuli
 * @date 2022/2/22
 */
@Service
public class RuleServiceImpl extends BaseService implements RuleService {

    @Override
    public TableDataInfo getRule(RuleVo ruleVo, PageDomain pageDomain) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        List<RuleVo> originalList= new ArrayList<>();
        for (GrayScaleTypeEnum grayScaleTypeEnum: GrayScaleTypeEnum.values()) {
            RuleVo vo = new RuleVo();
            vo.setType(grayScaleTypeEnum.getType());
            vo.setDealClass(grayScaleTypeEnum.getDealClass());
            vo.setDescription(grayScaleTypeEnum.getDescription());
            vo.setParameterNum(grayScaleTypeEnum.getParameterNum());
            vo.setExample(grayScaleTypeEnum.getExample());
            vo.setNeedParameterKey(grayScaleTypeEnum.getNeedParameterKey());
            originalList.add(vo);
        }
        //没有数据就不处理了
        if (originalList == null || originalList.size() <=0){
            rspData.setRows(originalList);
            rspData.setTotal(0);
            return rspData;
        }
        //查询条件过滤
        List<RuleVo> list = new ArrayList<>();
        if (StringUtils.isNotBlank(ruleVo.getType())){
            for (int i = 0; i < originalList.size(); i++) {
                if (originalList.get(i).getType().contains(ruleVo.getType().toUpperCase(Locale.ROOT))){
                    list.add(originalList.get(i));
                }
            }
            if (list == null || list.size() <=0){
                rspData.setRows(list);
                rspData.setTotal(0);
                return rspData;
            }
        }else{
            list = originalList;
        }
        int fromIndex=(pageDomain.getPageNum()-1)*pageDomain.getPageSize();
        int toIndex =fromIndex+pageDomain.getPageSize();
        if (fromIndex>list.size()){
            fromIndex =0;
            toIndex = 0;
        }else if(list.size() <= toIndex){
            toIndex = list.size();
        }
        List<RuleVo> pageList = list.subList(fromIndex,toIndex);
        rspData.setRows(pageList);
        rspData.setTotal(new PageInfo(originalList).getTotal());
        return rspData;
    }

    @Override
    public int getRulesNumber() {
        int size = 0;
        for (GrayScaleTypeEnum grayScaleTypeEnum: GrayScaleTypeEnum.values()) {
            size++;
        }
        return size;
    }


}
